using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Web;

namespace University.Models
{ 
    public class MarkRepository : IMarkRepository
    {
        UniversityContext context = new UniversityContext();

        public IQueryable<Mark> All
        {
            get 
            { 
                return context.Marks; 
            }
        }

        public IQueryable<Mark> AllIncluding(params Expression<Func<Mark, object>>[] includeProperties)
        {
            IQueryable<Mark> query = context.Marks;
            foreach (var includeProperty in includeProperties) {
                query = query.Include(includeProperty);
            }
            return query;
        }

        public Mark Find(int id)
        {
            return context.Marks.Find(id);
        }

        public void InsertOrUpdate(Mark mark)
        {
            if (mark.MarkId == default(int)) {
                // New entity
                // TO DO
                ProfessorRepository profRepo = new ProfessorRepository();
                var allProfessors = profRepo.All;
                
                int targetProfessorId = Convert.ToInt32(mark.ProfessorId);

                var prof = (from p in allProfessors 
                           where p.ProfessorId == targetProfessorId
                           select p).FirstOrDefault();
                mark.Professor = prof;
                //mark.ProfessorId = null;

                try
                {
                    context.Marks.Add(mark);
                }
                catch (Exception ex)
                {
                   var stackTrace =  ex.StackTrace;
                }

            } else {
                // Existing entity
                context.Entry(mark).State = EntityState.Modified;
            }
        }

        public void Delete(int id)
        {
            var mark = context.Marks.Find(id);
            context.Marks.Remove(mark);
        }

        public void Save()
        {
            context.SaveChanges();
        }

        public void Dispose() 
        {
            context.Dispose();
        }
    }

    public interface IMarkRepository : IDisposable
    {
        IQueryable<Mark> All { get; }
        IQueryable<Mark> AllIncluding(params Expression<Func<Mark, object>>[] includeProperties);
        Mark Find(int id);
        void InsertOrUpdate(Mark mark);
        void Delete(int id);
        void Save();
    }
}